package com.jinzheng.qianhai;
import com.jinzheng.qianhai.commont.DiscardOutServerHandler;
import com.jinzheng.qianhai.commont.DiscardServerHandler;
import com.jinzheng.qianhai.util.ByteArrayDecoder;
import com.jinzheng.qianhai.util.ByteArrayEncoder;
import com.jinzheng.qianhai.util.GBT32960Decoder;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import java.util.concurrent.TimeUnit;

/**
 * 启动netty服务端
 */
@SpringBootApplication
@Slf4j
public class NettyServiceApplication implements CommandLineRunner {

    /**
     * netty服务监听端口
     */
    @Value("${listent.server.port:15236}")
    private int serverPort;

    public static void main(String[] args) {
        SpringApplication.run(NettyServiceApplication.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        System.out.println("socket服务端监听运行端口：" + serverPort);
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 128)
                    //保持长连接，2小时无数据激活心跳机制
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    //将小的数据包包装成更大的帧进行传送，提高网络的负载
                    .childOption(ChannelOption.TCP_NODELAY, true)
                    //使用匿名内部类的形式初始化通道对象
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            //给pipeline管道设置处理器
                            socketChannel.pipeline().addLast(new IdleStateHandler(120, 0, 0, TimeUnit.SECONDS));
                            socketChannel.pipeline().addLast(new GBT32960Decoder());
                            socketChannel.pipeline().addLast(new ByteArrayEncoder());
                            //socketChannel.pipeline().addLast(new DiscardOutServerHandler());
                            socketChannel.pipeline().addLast(new DiscardServerHandler());
                        }
                    });//给workerGroup的EventLoop对应的管道设置处理器
            //绑定端口，同步等待成功
            ChannelFuture f = bootstrap.bind(serverPort).sync();
            //等待服务监听端口关闭
            f.channel().closeFuture().sync();
        } finally {
            //退出，释放线程资源
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }

}
